﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.Net.NetworkInformation;
using DGIS.SysSetting.Core.Model;

namespace DGIS.SysSetting.Core.Service.Win
{
    /// <summary>
    /// 网络设置
    /// </summary>
    public class NetworkService
    {
        /// <summary>
        /// 根据网卡名称获取网卡信息
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public Network Get(string name)
        {
            //IPHostEntry ipHostEntry = Dns.GetHostEntry(Dns.GetHostName());
            NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface adapter in networkInterfaces)
            {
                //判断是否是以太网连接
                bool ethernet = (adapter.NetworkInterfaceType == NetworkInterfaceType.Ethernet);

                if (ethernet && adapter.Description == name)
                {
                    //IP配置信息
                    IPInterfaceProperties ip = adapter.GetIPProperties();

                    Network item = new Network()
                    {
                        Name = name,
                        Dns = new List<string>(),
                        EnableDHCP = ip.GetIPv4Properties()== null?false:(ip.GetIPv4Properties().IsDhcpEnabled)
                    };

                    
                    for (int i = 0; i < ip.UnicastAddresses.Count; i++)
                    {
                        UnicastIPAddressInformation info = ip.UnicastAddresses[i];
                        if (!info.IPv4Mask.IsIPv6LinkLocal)
                        {
                            item.Ip = info.Address.ToString();//IP地址  
                            item.Mask = info.IPv4Mask.ToString();//子网掩码    
                            if (ip.GatewayAddresses.Count > 0)
                                item.Gateway = ip.GatewayAddresses[0].Address.ToString();//默认网关  
                        }
                    }

                    int dnsCount = ip.DnsAddresses.Count;
                    for (int i = 0; i < dnsCount; i++)
                    {
                        item.Dns.Add(ip.DnsAddresses[i].ToString());
                    }
                    return item;
                }
            }

            return null;
        }

        /// <summary>
        /// 获取网卡信息集合
        /// </summary>
        /// <returns></returns>
        public List<Network> GetList()
        {
            List<Network> items = new List<Network>();

            NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface adapter in networkInterfaces)
            {
                Network item = Get(adapter.Description);
                if (item != null)
                    items.Add(item);
            }

            return items;
        }

        /// <summary>
        /// 网卡信息设置
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public bool Set(Network item)
        {
            ManagementClass managementClass = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection managementObjectCollection = managementClass.GetInstances();

            foreach (ManagementObject managementObject in managementObjectCollection)
            {
                bool ipEnabled = (bool)managementObject["IPEnabled"];
                if (ipEnabled)
                {
                    string name = managementObject["Description"].ToString();

                    if (name == item.Name)
                    {
                        //存储旧的数据，方便还原
                        object oldIp, oldMask, oldGetway, oldDns;
                        oldIp = managementObject["IPAddress"];
                        oldMask = managementObject["IPSubnet"];
                        oldGetway = managementObject["DefaultIPGateway"];
                        oldDns = managementObject["DNSServerSearchOrder"];

                        Network oldItem = new Network()
                        {
                            Name = item.Name,
                            Ip = (oldIp as string[])[0],
                            Mask = (oldMask as string[])[0],
                            Gateway = (oldGetway as string[])[0],
                            Dns = (oldDns as string[]).ToList()
                        };

                        if (item.EnableDHCP)
                        {
                            //自动获取IP
                            if (!(bool)managementObject["DHCPEnabled"])
                            {
                                foreach (PropertyData data in managementObject.Properties)
                                {
                                    Console.WriteLine(data.Name + ":" + data.Value);
                                }
                                ManagementBaseObject enableStaticManage = managementObject.GetMethodParameters("EnableDHCP");
                                ManagementBaseObject outPar = managementObject.InvokeMethod("EnableDHCP", enableStaticManage, null);
                                return GetResult(outPar);
                            }
                        }
                        else
                        {
                            //设置固定IP
                            ManagementBaseObject enableStaticManage = managementObject.GetMethodParameters("EnableStatic");
                            enableStaticManage["IPAddress"] = new string[] { item.Ip }; 
                            enableStaticManage["SubnetMask"] = new string[] { item.Mask };
                            ManagementBaseObject outPar = managementObject.InvokeMethod("EnableStatic",
                                enableStaticManage, null);
                            bool result1 = GetResult(outPar);

                            ManagementBaseObject setGatewaysManage = managementObject.GetMethodParameters("SetGateways");
                            setGatewaysManage["DefaultIPGateway"] = new string[] { item.Gateway };
                            outPar = managementObject.InvokeMethod("SetGateways", setGatewaysManage, null);
                            bool result2 = GetResult(outPar);

                            ManagementBaseObject dnsManage = managementObject.GetMethodParameters("SetDNSServerSearchOrder");
                            dnsManage["DNSServerSearchOrder"] = item.Dns.ToArray();
                            outPar = managementObject.InvokeMethod("SetDNSServerSearchOrder", dnsManage, null);
                            bool result3 = GetResult(outPar);

                            if (!result1 || !result2 || !result3)
                            {
                                //更新失败还原
                                bool result = Set(oldItem);
                                return false;
                            }
                            else
                            {
                                //更新成功
                                return true;
                            }
                        }
                    }
                }
            }

            return false;
        }

        /// <summary>
        /// 转换网卡配置结果
        /// </summary>
        /// <param name="mbo"></param>
        /// <returns></returns>
        private bool GetResult(ManagementBaseObject mbo)
        {
            return Int64.Parse(mbo["ReturnValue"].ToString()) == 0;
        }
    }
}
